import axios from 'axios'

const service = axios.create({
  baseURL: 'http://127.0.0.1:5000/api',
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    console.log('响应数据:', response.data)
    return response.data
  },
  error => {
    console.error('请求错误:', error)
    if (error.response && error.response.status === 401) {
      // token过期或无效，跳转到登录页
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

export default service